package com.community.sqlapp.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.GetObjectRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.File;

@Configuration
public class TencentCosUtil {

    @Value("${tencent.cos.secretid}")
    private String secretId;
    @Value("${tencent.cos.secretkey}")
    private String secretKey;
    @Value("${tencent.cos.region}")
    private String region;

    /**
     * 调用静态方法getCosClient()就会获得COSClient实例
     * @return
     */
    @Bean
    public COSClient cosClient() {
        // 1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2.1 设置存储桶的地域（上文获得）
        Region regions = new Region(region);
        ClientConfig clientConfig = new ClientConfig(regions);

        // 2.2 使用https协议传输
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        // 返回COS客户端
        return cosClient;
    }

    // 静态上传方法
    public static String uploadFile(File file, String cosPath, String bucket, COSClient cosClient) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, cosPath, file);
        cosClient.putObject(putObjectRequest);
        // 拼接url（假设私有读，实际可用签名url或自定义域名）
        String url = String.format("https://%s.cos.%s.myqcloud.com/%s", bucket, cosClient.getClientConfig().getRegion().getRegionName(), cosPath);
        return url;
    }
} 